package top.syfy.log4j.servlet;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.PropertyConfigurator;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * 在J2EE应用使用Log4j，必须先在启动服务时加载Log4j的配置文件并进行初始化,可以在web.xml中进行
 *
 * @author syfy
 * @date 2020/12/28
 */
public class Log4JInitServlet extends HttpServlet {

    public Log4JInitServlet() {
        super();
    }

    /**
     * 在启动服务时加载Log4j的配置
     *
     * @param config 配置
     * @throws ServletException 异常
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        // 从web.xml文件中获取log4j的配置文件的路径
        String log4jLocation = config.getInitParameter("log4j-properties-location");
        // 若未读取到配置文件的路径, 则使用默认的配置
        if (log4jLocation == null) {
            System.err.println("未读取到指定的配置文件,将使用默认的配置文件进行初始化");
            BasicConfigurator.configure();
        } else {
            // 读取到配置文件的路径, 则使用指定的配置
            String log4jProp = config.getServletContext().getRealPath("/") + log4jLocation;
            if (!(new File(log4jProp)).exists()) {
                System.err.println("指定的配置文件" + log4jProp + "不存在,将使用默认的配置文件进行初始化");
                BasicConfigurator.configure();
            } else {
                System.out.println("读取到配置文件的路径, 则使用指定的配置");
                PropertyConfigurator.configure(log4jProp);
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }

    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        super.service(req, res);
    }
}
